package com.evil.common.core.entity;

import com.alibaba.fastjson.JSON;
import com.evil.common.core.enums.BaseEnum;
import lombok.Getter;
import lombok.Setter;

import java.io.Serial;
import java.io.Serializable;

/**
 * @author liyang
 */
public class R<T> implements Serializable {

    @Serial
    private static final long serialVersionUID = 1L;

    @Getter
    @Setter
    private int code;

    @Getter
    @Setter
    private String message;

    @Getter
    @Setter
    private T data;

    private R(int code, String message, T data) {
        this.code = code;
        this.data = data;
        this.message = message;
    }

    public R() {
        this.code = BaseEnum.SUCCESS.getCode();
        this.message = BaseEnum.SUCCESS.getMessage();
        this.data = null;
    }

    public static <T> R<T> success() {
        return new R<>(BaseEnum.SUCCESS.getCode(), BaseEnum.SUCCESS.getMessage(), null);
    }

    public static <T> R<T> success(String message) {
        return new R<>(BaseEnum.SUCCESS.getCode(), message, null);
    }

    public static <T> R<T> success(T data) {
        return new R<>(BaseEnum.SUCCESS.getCode(), BaseEnum.SUCCESS.getMessage(), data);
    }

    public static <T> R<T> success(String message, T data) {
        return new R<>(BaseEnum.SUCCESS.getCode(), message, data);
    }

    public static <T> R<T> error() {
        return new R<>(BaseEnum.ERROR.getCode(), BaseEnum.ERROR.getMessage(), null);
    }

    public static <T> R<T> error(String message) {
        return new R<>(BaseEnum.ERROR.getCode(), message, null);
    }

    public static <T> R<T> error(BaseEnum baseEnum) {
        return new R<>(baseEnum.getCode(), baseEnum.getMessage(), null);
    }

    public static <T> R<T> error(BaseEnum baseEnum, String message) {
        if (message == null) {
            message = baseEnum.getMessage();
        }
        return new R<>(baseEnum.getCode(), message, null);
    }

    public static <T> R<T> error(BaseEnum baseEnum, String message, T data) {
        if (message == null) {
            message = baseEnum.getMessage();
        }
        return new R<>(baseEnum.getCode(), message, data);
    }

    public static <T> R<T> error(int code, String message) {
        return new R<>(code, message, null);
    }

    public static <T> R<T> error(int code, String message, T data) {
        return new R<>(code, message, data);
    }

    public boolean succeed() {
        return BaseEnum.SUCCESS.getCode() == this.code;
    }

    public boolean unSucceed() {
        return !this.succeed();
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}
